<template>
  <el-container class="video-container">
    <el-header>
      <el-page-header :icon="ArrowLeft" @back="goBack">
        <template #content>
          <span class="text-primary font-600 mr-3">视频播放</span>
        </template>
      </el-page-header>
    </el-header>

    <el-main>
      <el-row :gutter="20">
        <el-col :span="16">
          <div class="video-viewer" id="player-container">
            <!-- 播放器将在这里初始化 -->
          </div>
        </el-col>

        <el-col :span="8">
          <el-card class="notes-card mb-3">
            <template #header>
              <div class="card-header">学习笔记</div>
            </template>
            <div class="qa-list">
              <div v-for="nt in notesList" :key="nt.id">
                <p>{{ nt.content }}</p>
                <el-divider></el-divider>
              </div>
            </div>
            <el-input
              type="textarea"
              :rows="5"
              placeholder="记录你的学习笔记..."
              v-model="notes"
            ></el-input>

            <div ref="notesEnd"></div>

            <el-button type="primary" class="mt-2" @click="saveNotes"
              >保存笔记
            </el-button>
          </el-card>

          <el-card class="qa-card">
            <template #header>
              <div class="card-header">问题讨论</div>
            </template>
            <div class="qa-list">
              <div
                v-for="(qa, index) in qaList"
                :key="qa.id || index"
                class="qa-item"
              >
                <p><strong>Q:</strong> {{ qa.questions.content }}</p>
                <p v-for="ans in qa.answers">
                  <strong>A:</strong> {{ ans.content || "暂无回答" }}
                </p>

                <!-- 教师可以回答问题 -->
                <div v-if="isTeacher && !qa.answer" class="answer-form mt-2">
                  <el-input
                    type="textarea"
                    :rows="2"
                    placeholder="输入回答..."
                    v-model="qa.tempAnswer"
                    class="mb-2"
                  ></el-input>
                  <el-button
                    type="success"
                    size="small"
                    @click="answerQuestion(qa.questions.id, qa.tempAnswer)"
                  >
                    提交回答
                  </el-button>
                </div>
                <el-divider></el-divider>
              </div>
              <div ref="qaEnd"></div>
            </div>
            <el-input
              type="textarea"
              :rows="3"
              placeholder="提出你的问题..."
              v-model="newQuestion"
              class="mb-2"
            ></el-input>
            <el-button type="primary" @click="submitQuestion"
              >提交问题
            </el-button>
          </el-card>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, nextTick, onMounted, onUnmounted, computed } from "vue";
import { ArrowLeft } from "@element-plus/icons-vue";
import { useRoute, useRouter } from "vue-router";
import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/user";
import { useCourseStore } from "@/stores/course";
import common_util from "@/util/common_util";

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const courseStore = useCourseStore();

// 获取当前用户ID和角色信息
const userId = computed(() => userStore.user?.id);
const isTeacher = computed(() => userStore.isTeacher);
const isStudent = computed(() => userStore.isStudent);

const videoUrl = ref(route.query.url ? route.query.url.toString() : "");
const courseId = ref(
  route.query.courseId ? parseInt(route.query.courseId) : null,
);
const notes = ref("");
const newQuestion = ref("");
const player = ref(null);
const currentTime = ref(0);
const duration = ref(0);
const progressTimer = ref(null);
const lastReportedTime = ref(0);

// 使用courseStore中的notes数据
const notesList = computed(() => courseStore.notes || []);
// 使用courseStore中的questions数据
const qaList = computed(() => courseStore.questions || []);

const notesEnd = ref(null);
const qaEnd = ref(null);

// 格式化时间为 mm:ss 格式
const formatTime = (seconds) => {
  if (!seconds) return "00:00";
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
};

// 改变播放速度
const changeSpeed = (speed) => {
  if (player.value) {
    player.value.setSpeed(speed);
  }
};

// 记录播放进度
const recordProgress = () => {
  if (player.value) {
    currentTime.value = player.value.getCurrentTime() || 0;
    duration.value = player.value.getDuration() || 0;

    // 每30秒或播放进度变化超过5%时向服务器报告进度
    const currentTimeInSeconds = Math.floor(currentTime.value);
    const durationInSeconds = Math.floor(duration.value);
    const progressPercentage =
      durationInSeconds > 0
        ? (currentTimeInSeconds / durationInSeconds) * 100
        : 0;

    // 检查是否需要报告进度
    const timeSinceLastReport = currentTimeInSeconds - lastReportedTime.value;
    const shouldReportProgress =
      timeSinceLastReport >= 30 ||
      Math.abs(
        progressPercentage - (lastReportedTime.value / durationInSeconds) * 100,
      ) >= 5;

    if (
      shouldReportProgress &&
      durationInSeconds > 0 &&
      userId.value &&
      courseId.value
    ) {
      // 使用courseStore的updateProgress方法报告进度
      courseStore.updateProgress(userId.value, currentTimeInSeconds);
      lastReportedTime.value = currentTimeInSeconds;
      console.log("进度已报告:", progressPercentage.toFixed(2) + "%");
    }
  }
};

// 向服务器报告进度
const reportProgressToServer = async (currentTime, duration, percentage) => {
  if (!userId.value || !courseId.value) return;

  try {
    // 使用courseStore的updateProgress方法
    courseStore.updateProgress(courseId.value,userId.value, currentTime);
    console.log("进度已报告:", percentage.toFixed(2) + "%");
  } catch (error) {
    console.error("报告进度失败:", error);
  }
};

onMounted(async() => {
  // 确保视频URL存在
  if (!videoUrl.value) {
    console.error("视频URL不存在");
    return;
  }

  const currentCourseId = route.query.courseId ? parseInt(route.query.courseId) : null;
  const resourceId = route.query.resourceId ? parseInt(route.query.resourceId) : null;

  console.log("当前课程ID:", currentCourseId);
  console.log("当前资源ID:", resourceId);
  if (resourceId && currentCourseId && !courseStore.chooseResource) {
    // 1. 获取课程的详细信息，这通常会填充课程资源列表 (courseResources)
    await courseStore.getCourseDetail(currentCourseId);
    
    // 2. 在资源列表中查找匹配的资源
    const currentResource = courseStore.courseResources.find(r => r.id === resourceId);
    
    if (currentResource) {
      // 3. 将找到的资源设置回 store，从而恢复状态
      courseStore.chooseResource = currentResource;
      console.log("已通过URL参数恢复 chooseResource:", courseStore.chooseResource);
    }
  }
  // 初始化播放器
  if (typeof Aliplayer !== "undefined") {
    player.value = new Aliplayer(
      {
        id: "player-container", // 播放器容器的 ID
        width: "100%", // 播放器宽度
        height: "500px", // 播放器高度
        autoplay: true, // 自动播放
        isLive: false, // 不是直播
        rePlay: false, // 不重播
        playsinline: true, // 行内播放
        preload: true, // 预加载视频
        controlBarVisibility: "hover", // 鼠标悬停时显示控制栏
        useH5Prism: true, // 使用H5播放器
        source: videoUrl.value, // 使用路由参数中的视频 URL
      },
      function (player) {
        console.log("播放器创建成功");

        // 监听播放器事件
        player.on("ready", () => {
          console.log("播放器准备就绪");
          duration.value = player.getDuration() || 0;

          // 获取之前的播放进度
          if (
            userId.value &&
            courseStore.chooseResource &&
            courseStore.chooseResource.id
          ) {
            courseStore.getProgress(
              userId.value,
              courseStore.chooseResource.id,
            );
            // 如果有进度，设置播放器从该位置开始播放
            if (courseStore.progress > 0) {
              player.seek(courseStore.progress);
            }
          }
        });

        player.on("play", () => {
          console.log("视频开始播放");
        });

        player.on("pause", () => {
          console.log("视频暂停");
          // 暂停时也报告一次进度
          recordProgress();
        });

        player.on("ended", () => {
          console.log("视频播放结束");
          // 播放结束时报告100%进度
          reportProgressToServer(duration.value, duration.value, 100);
        });
      },
    );

    // 设置定时器，每秒更新一次播放进度
    progressTimer.value = setInterval(recordProgress, 1000);

    // 加载笔记和问题
    if (userId.value && courseId.value) {
      courseStore.getNotes(userId.value, courseId.value);
      courseStore.getQuestionAndAnswers(userId.value, courseId.value);
    }
  } else {
    console.error("Aliplayer未加载，请确保CDN正确引入");
  }
});

onUnmounted(() => {
  // 组件卸载时清除定时器和销毁播放器
  if (progressTimer.value) {
    clearInterval(progressTimer.value);
  }

  if (player.value) {
    player.value.dispose();
    player.value = null;
  }
});

const goBack = () => {
  // 返回前报告最后进度
  recordProgress();
  router.go(-1);
};

const saveNotes = async () => {
  if (!notes.value.trim()) {
    ElMessage.warning("笔记内容不能为空！");
    return;
  }

  if (!userId.value || !courseId.value) {
    ElMessage.warning("用户信息或课程信息不完整，无法保存笔记");
    return;
  }

  try {
    // 使用courseStore的addNote方法保存笔记
    console.log("保存笔记:", notes.value);
    console.log("用户ID:", userId.value);
    await courseStore.addNote(notes.value, userId.value, courseId.value);

    // 清空输入框
    notes.value = "";

    // 重新获取笔记列表
    await courseStore.getNotes(userId.value, courseId.value);

    nextTick(() => {
      notesEnd.value?.scrollIntoView({ behavior: "smooth" });
    });
  } catch (error) {
    console.error("保存笔记失败:", error);
    ElMessage.error("保存笔记失败，请稍后重试");
  }
};

const submitQuestion = async () => {
  if (!newQuestion.value.trim()) {
    ElMessage.warning("问题内容不能为空！");
    return;
  }

  if (!userId.value || !courseId.value) {
    ElMessage.warning("用户信息或课程信息不完整，无法提交问题");
    return;
  }

  try {
    // 使用common_util提交问题
    const content = newQuestion.value;
    await new Promise((resolve, reject) => {
      common_util.post(
        "/api/study/ask",
        {
          userId: userId.value,
          courseId: courseId.value,
          content: content,
        },
        {},
        (data) => {
          ElMessage.success("问题提交成功");
          resolve(data);
        },
        (message) => {
          ElMessage.error(`提交问题失败: ${message}`);
          reject(message);
        },
      );
    });

    // 清空输入框
    newQuestion.value = "";

    // 重新获取问题列表
    await courseStore.getQuestionAndAnswers(userId.value, courseId.value);

    nextTick(() => {
      qaEnd.value?.scrollIntoView({ behavior: "smooth" });
    });
  } catch (error) {
    console.error("提交问题失败:", error);
    ElMessage.error("提交问题失败，请稍后重试");
  }
};

// 教师回答问题
const answerQuestion = async (questionId, answerContent) => {
  if (!isTeacher.value) {
    ElMessage.warning("只有教师可以回答问题");
    return;
  }

  if (!answerContent || !answerContent.trim()) {
    ElMessage.warning("回答内容不能为空");
    return;
  }

  try {
    await courseStore.answerQuestion(answerContent, userId.value, questionId);

    // 重新获取问题列表
    await courseStore.getQuestionAndAnswers(userId.value, courseId.value);
  } catch (error) {
    console.error("回答问题失败:", error);
    ElMessage.error("回答问题失败，请稍后重试");
  }
};
</script>

<style scoped>
.video-container {
  height: 100vh;
  padding: 20px;
}

.video-viewer {
  width: 100%;
  height: 70vh; /* 固定高度 */
  display: flex;
  flex-direction: column; /* 垂直布局 */
  justify-content: center;
  align-items: center;
  background-color: #000;
  border-radius: 8px;
  position: sticky; /* 固定位置 */
  top: 0; /* 固定在顶部 */
  z-index: 10; /* 确保在其他内容之上 */
}

.video-player {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.player-controls {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.notes-card,
.qa-card {
  margin-bottom: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.qa-item {
  margin-bottom: 10px;
}

.qa-list {
  max-height: 200px;
  overflow-y: auto;
  margin-bottom: 15px;
}
</style>
